package com.bing.task.v1;

import com.bing.Utils;
import com.bing.entity.Question;
import com.bing.entity.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * Created by kaibb on 15-11-14.
 */
public class FetchParseQuestion extends RecursiveTask<QuestionResult> {
    private static final Logger LOGGER = LoggerFactory.getLogger(FetchParseQuestion.class);
    private List<Question> questions;

    public FetchParseQuestion(List<Question> questions) {
        this.questions = questions;
    }

    @Override
    protected QuestionResult compute() {
        if (questions.size() <= 20) {
            QuestionResult questionResult = new QuestionResult();
            for (Question question : questions) {
                Utils.fetchQuestion(question);
                if (question.getStatus() == Status.OK) {
                    questionResult.addAccounts(Utils.fetchAccounts(question.getContent()));
                    questionResult.addAnswers(Utils.parse2Answer(question.getQid(), question.getContent()));
                    question.toFile();
                }
            }
            questionResult.addQuestions(questions);
            LOGGER.info("子任务完成。");
            return questionResult;
        }
        FetchParseQuestion left = new FetchParseQuestion(questions.subList(0, questions.size() / 2));
        left.fork();
        FetchParseQuestion right = new FetchParseQuestion(questions.subList(questions.size() / 2, questions.size()));
        right.fork();
        QuestionResult leftJoin = left.join();
        QuestionResult rightJoin = right.join();

        return leftJoin.addQuestionResult(rightJoin);
    }
}
